package com.letv.so.service.thrift.detail;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import net.rubyeye.xmemcached.MemcachedClient;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import serving.ResultDocInfo;

import com.letv.so.bean.AlbumBean;
import com.letv.so.bean.VideoBean;
import com.letv.so.constants.Constants;
import com.letv.so.service.QueryDataService;
import com.letv.so.util.BisUtil;
import com.letv.so.util.StringUtil;

/**
 * thrift detail interface : static mathod for common use
 */
public class CommonDetail {

    /**
     * Logger
     */
    private static Logger LOGGER = LoggerFactory.getLogger(CommonDetail.class);

    /**
     * !!!!!!!it's obligatory to synchronize wiki after change code,the wiki page is:
     * http://wiki.letv.cn/pages/viewpage.action?pageId=61197752
     * get detail:
     * 1.leso album       -- Constants.LESO_ALBUM_PERFIX
     * 2.leso video       -- Constants.LESO_VIDEO_PERFIX
     * 3.leso short video -- Constants.LESO_SHORT_VIDEO_PERFIX
     * 4.letv album       -- Constants.VRS_ALBUM_PERFIX
     * 5.letv video       -- Constants.LETV_VIDEO_PERFIX
     * 6.cp               -- Constants.CP_PERFIX
     * TODO now only can get cp detail.
     * TODO all detail will be obtained by this method in future
     * @param queryDataService QueryDataService, get data from memached.It's used to get two tytes of data:
     *                                           1.json data stored by offlinetask
     *                                           2.thrift data stored by offlinetask
     * @param memcachedClient MemcachedClient, get data from memached.It's used to get thrift data stored by pipline
     * @param letvOrginalId String, letv perfix with common id from each source. for more information please visit the page following:
     *                              http://wiki.letv.cn/pages/viewpage.action?pageId=52863107        
     * @param timeStamp get by Long, System.currentTimeMillis() when request comes.It's used to mark the request
     * @param fromIndex int, TODO begin id while request for a list(now only have cp):
     *                       6.cp -- begin id of album index at album list in cp
     * @param pageSize int, TODO element numbuer while request for a list(now only have cp):
     *                      6.cp -- element numbuer of album index at album list in cp
     * @param cpRequestType int, 0--album 1--video
     * @return ResultDocInfo, return null if there is no data or have errors
     */
    public static ResultDocInfo getDetail(QueryDataService queryDataService, MemcachedClient memcachedClient, String letvOrginalId, Long timeStamp, int fromIndex, int pageSize, int cpRequestType) {
        if(null == queryDataService || null == memcachedClient || StringUtils.isBlank(letvOrginalId) || null == timeStamp || fromIndex < 0 || pageSize < 0) {
            return null;
        }
        ResultDocInfo result = null;
        if(letvOrginalId.indexOf(Constants.CP_PERFIX) == 0) {
            result = CpDetail.getCp(queryDataService, memcachedClient, letvOrginalId, timeStamp, fromIndex, pageSize, cpRequestType);
        }
        return result;
    }

    /**
     * TODO set sub video list to album of leso
     * this method will not check parameters which passed in
     * @param timeStamp String, get by Long, System.currentTimeMillis() when request comes.It's used to mark the request
     * @param soKey String, key word to select cbase of leso album
     * @param album AlbumBean, leso album
     * @param fromIndex int, begin index of sub video list
     * @param pageSize int, video count of sub video list
     */
    static void setVideoList(String timeStamp, String soKey, AlbumBean album, int fromIndex, int pageSize) {
        String url = album.getUrl();
        String subSrc = album.getSubSrc();
        if (!StringUtil.isBlank(url) && !StringUtil.isBlank(subSrc) && (Constants.WEBSITE_NETS.equals(subSrc) || "pan".endsWith(subSrc))) {
            int len = url.lastIndexOf('/') + 1;
            album.setPanid(url.substring(len));
            album.setSubSrc(Constants.WEBSITE_NETS);
        } else {
            album.setPanid("");
        }
        List<VideoBean> videoList = new ArrayList<VideoBean>();
        List<String>  tags = new ArrayList<String>();
        String videoPlayUrls = album.getVideoPlayUrls();
        //死链map
       if (!StringUtil.isBlank(videoPlayUrls)) {
            String avids = album.getOrderlist();
           List<String> orders = new ArrayList<String>();
           String[] videoArray = videoPlayUrls.split(";");
            String[] vidArray = avids.split(",");
            String[] durationsArray = album.getVideo_durations() == null ? new String[0]
                    : album.getVideo_durations().split(",");
            String[] typeArray = album.getVideo_types() == null ? new String[0] : album.getVideo_types().split(",");
           for (String vid : videoArray) {
               String[] videoFileds = vid.split("\\|");
               if (videoFileds.length==1) {//过滤不规范的数据
                   continue;
               }
               orders.add(videoFileds[0]);
           }
           List<String> vidLists = Arrays.asList(videoArray);
           int size = vidLists.size();
           int toIndex = fromIndex + pageSize;
           if (fromIndex >= size) {
               return;
           } else if ( fromIndex<size && toIndex > size ) {
                   toIndex = size;
           }
           List<String> retVids = new ArrayList<String>();
           List<String> retInfos = BisUtil.subList(fromIndex,toIndex,BisUtil.getList(album.getIntro()));
           List<String> subNames = BisUtil.subList(fromIndex,toIndex,BisUtil.getList(album.getVideoSubNames()));
           List<String> externalIds = BisUtil.subList(fromIndex, toIndex, BisUtil.getList(album.getExternalIds()));
           List<String> letvVids = BisUtil.subList(fromIndex, toIndex, BisUtil.getList(album.getVids()));
           List<String> letvOrininalSvidList = BisUtil.subList(fromIndex, toIndex, BisUtil.getList(album.getLetvOrininalSvids()));
           // 只有SARSS端需要外网流截图
           List<String> images = new ArrayList<String>();
            if (Constants.WEBSITE_LETV.equals(subSrc)) {
               images = BisUtil.subList(fromIndex,toIndex,BisUtil.getList(album.getVideoImages()));
           } else {
               images = BisUtil.subList(fromIndex,toIndex,BisUtil.getList(album.getVideoImages()));
           }
           List<String> deadinfo = new ArrayList<String>();
           List<String> payPlatforms = BisUtil.subList(fromIndex,toIndex,BisUtil.getList(album.getPayPlatform()));
           List<String> downloadPlatforms = BisUtil.subList(fromIndex,toIndex,BisUtil.getList(album.getDownloadPlatform()));
           List<String> ispays = BisUtil.subList(fromIndex,toIndex,BisUtil.getList(album.getIsPays()));
           List<String> mids = BisUtil.subList(fromIndex,toIndex,BisUtil.getList(album.getMids()));
           ArrayList<String> deadlinkList = new ArrayList<String>();
           String deadlinks = album.getDeadlinks();
           BisUtil.convertStr2List(deadlinks,deadlinkList);
           retVids = vidLists.subList(fromIndex, toIndex);
           deadinfo = deadlinkList.subList(fromIndex, toIndex);
           LOGGER.info(timeStamp+" ,"+soKey+" SRC_LESO retVids fromIndex="+fromIndex+",toIndex="+toIndex+",videolist="+retVids.size());
           ArrayList<String> globalVids = new ArrayList<String>();
           BisUtil.convertStr2List(album.getUnIds(), globalVids);
           List<String> subGlobalVids = globalVids.subList(fromIndex, toIndex);
           String aid = album.getAid();
           String category = album.getCategory();
           for (int i=0;i<retVids.size();i++) {
               String vid = retVids.get(i);
               if (StringUtil.isNotBlank(vid)) {
                   String[] videoFileds = vid.split("\\|");
                   if (videoFileds.length==1) {//过滤不规范的数据
                       continue;
                   }
                   String[] videoInfo = retInfos.size() > i ? retInfos.get(i).split("\\|") : new String[0];
                   String[] subName = subNames.size() > i ? subNames.get(i).split("\\|") : new String[0];
                   String[] image = images.size() > i ? images.get(i).split("\\|") : new String[0];
                   String[] ispayv = ispays.size() > i ? ispays.get(i).split("\\|") : new String[0];
                   String[] payPlatform = payPlatforms.size() > i ? payPlatforms.get(i).split("\\|") : new String[0];
                   String[] downPlatform = downloadPlatforms.size() > i ? downloadPlatforms.get(i).split("\\|") : new String[0];
                   String[] externelid = externalIds.size() > i ? externalIds.get(i).split("\\|") : new String[0];
                   String[] vids = letvVids.size() > i ? letvVids.get(i).split("\\|") : new String[0];
                   String[] letvOrininalSvidArray = letvOrininalSvidList.size() > i ? letvOrininalSvidList.get(i).split("\\|") : new String[0];
                   String[] mid = mids.size() > i ? mids.get(i).split(",") : new String[0];
                   VideoBean video = new VideoBean();
                   video.setDataType(Constants.VIDEO);
                   video.setAid(aid);
                   video.setCategory(category);
                   video.setAorder(videoFileds[0]);
                   video.setUrl(videoFileds[1]);
                    video.setSvid(vidArray.length > i ? vidArray[i] : null);
                    video.setDuration(durationsArray.length > i ? durationsArray[i] : null);
                    video.setVideoType(typeArray.length > i ? typeArray[i] : null);
                   video.setExternal_id(externelid.length > 1 ? externelid[1] : "");
                   video.setVid(vids.length > 1 ? vids[1] : null);
                   video.setName(videoInfo.length > 1 ? videoInfo[1] : "");
                   video.setSubName(subName.length > 1 ? subName[1] : video.getName());
                   video.setIsPay(ispayv.length > 1 ? ispayv[1] : "0");
                   video.setPayPlatform(payPlatform.length > 1 ? payPlatform[1] : null);
                   video.setDownloadPlatform(downPlatform.length > 1 ? downPlatform[1] : null);
                   video.setLetvOrininalSvid(letvOrininalSvidArray.length > 1 ? letvOrininalSvidArray[1] : null);
                   if (image.length > 1) {
                       try {
                           video.setImages(image[1]);
                       }catch(Exception e){
                           LOGGER.error("parse images for single video,error album id="+album.getAid(),e);
                       }
                   } 
                   tags.add(videoFileds[0]);
                   String videoUrl = video.getUrl();
                    if (!StringUtil.isBlank(videoUrl) && (!StringUtil.isBlank(subSrc))
                            && (Constants.WEBSITE_NETS.equals(subSrc) || "pan".endsWith(subSrc))) {
                       int len = videoUrl.lastIndexOf('/') + 1;
                       video.setVideoPanid(videoUrl.substring(len));
                   } else {
                       video.setVideoPanid("");
                   }
                   //添加死链
                   if (deadinfo.size() > i) {
                       video.setDeadlink(deadinfo.get(i));
                   } else {
                       LOGGER.debug(timeStamp+" ,"+soKey+",SRC_LESO videoPlayUrls 与 deadlinks 不匹配 ");
                       video.setDeadlink("0");
                   }
                   if(subGlobalVids.size() > i) {
                       video.setUnid(subGlobalVids.get(i));
                   }
                   //每个视频添加唯一全局id
                   String porder = "1";
                   if (StringUtils.isNotBlank(video.getAorder())) {
                       porder = video.getAorder();
                   }
                   video.setMid(mid.length > 1 ? mid[1] : "");
                   video.setGlobal_vid(aid+"_"+porder+"_"+BisUtil.MD5(video.getUrl()));
                   BisUtil.setPayAndDownFlag(video);
                   videoList.add(video);
               } else {
                   tags.add("null");
               }
           }
           album.setSomePropertyNull();
           long st3 = System.currentTimeMillis();
           LOGGER.debug(timeStamp+" ,"+soKey+",SRC_LESO tagList, cost time8=" + (System.currentTimeMillis()-st3));
           if (videoList.size() > 0) {
               LOGGER.warn("videolist size={}",videoList.size());
               album.setVideoList(videoList);
           }
       }
    }
}
